// fast4j - Fast & Agile Service Tools for Java
// Copyright (C) 2007 Alexandre ROMAN
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

// $Id: ApplicationDescriptorReader.java 51 2007-04-08 12:37:12Z alexandre.roman $

package fast4j.ace;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.thoughtworks.xstream.XStream;

/**
 * Application descriptor reader. This class is responsible for parsing XML and
 * creating {@link ApplicationCreator} instances. Here is a sample XML file:
 * 
 * <pre>
 * &lt;application&gt;
 *     &lt;id&gt;appid&lt;/id&gt;
 *     &lt;name&gt;appname&lt;/id&gt;
 *     &lt;version&gt;appversion&lt;&lt;/version&gt;
 *     &lt;package&gt;org.apppackage&lt;/package&gt;
 *     &lt;properties&gt;
 *         &lt;prop1&gt;value1&lt;/prop1&gt;
 *     &lt;/properties&gt;
 * &lt;/application&gt;
 * </pre>
 * 
 * This class is <strong>thread-safe</strong>.
 * @author alexandre.roman
 */
public class ApplicationDescriptorReader {
    private final XStream xstream = new XStream();
    
    public ApplicationDescriptorReader() {
        xstream.alias("application", ApplicationDescriptor.class);
        xstream.aliasField("package", ApplicationDescriptor.class,
            "rootPackage");
        xstream.registerConverter(new ApplicationDescriptorPropertyConverter());
    }
    
    /**
     * Build an application descriptor from an XML file.
     */
    public ApplicationDescriptor read(InputStream input) throws IOException {
        final ApplicationDescriptor desc = (ApplicationDescriptor) xstream
                .fromXML(new InputStreamReader(input));
        
        try {
            desc.validate();
        } catch (IllegalArgumentException e) {
            final IOException e2 = new IOException(
                    "Invalid application descriptor");
            e2.initCause(e);
            throw e2;
        }
        
        return desc;
    }
}
